#include<iostream>
#include<pthread.h>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<typeinfo>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

#define num 4
// #define uint (unsigned int)
using Uint = unsigned long long;
int main()
{
    pthread_t t[num];
    auto active = [](void* args) 
    ->void*
    {
        std::string name = static_cast<const char*> (args);
        while (1)
        {
            pthread_mutex_lock(&mutex);
            // zdl:: 没有对资源的持续判定
            pthread_cond_wait(&cond, &mutex);
            cout << "I am a thread, named " << name 
            << ". I am activated!"<< endl;
            pthread_mutex_unlock(&mutex);
        }
        return nullptr;
    };
    for (int i = 0; i < num; i++)
    {
        auto str = string("thread-") + to_string(i);
        auto src = (void*) (str.c_str());
        pthread_create(&t[i], nullptr, active, src);
    }
    sleep(1);
    printf("Main thread ctl is activated!\n");
    while (1)
    {
        cout << "Wake up thread..." << endl;
        pthread_cond_signal(&cond);
        sleep(1);
    }
    for (int i = 0; i < num; i++)
    {
        pthread_join(t[i], nullptr);
    }
    
    return 0;
}
